package com.fxd.shopping.es.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fxd.common.param.SkuUpEsParam;
import com.fxd.shopping.es.config.ElasticSearchConfig;
import com.fxd.shopping.es.enums.EsIndexNames;
import com.fxd.shopping.es.service.ProductSaveService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @SneakyThrows
    @Override
    public boolean productStatusUp(List<SkuUpEsParam> skuUpEsParams) {
        if (CollectionUtils.isEmpty(skuUpEsParams)) {
            log.info("上架数据为空...");
            return false;
        }
        // kibana建索引
        // 批量保存数据
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuUpEsParam skuUpEsParam : skuUpEsParams) {
            // 构造请求
            IndexRequest indexRequest = new IndexRequest(EsIndexNames.PRODUCT_INDEX.getValue());
            indexRequest.id(skuUpEsParam.getSkuId().toString());
            String jsonString = JSONObject.toJSONString(skuUpEsParam);
            indexRequest.source(jsonString, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);

        // TODO 如果批量错误，需要处理
        if (bulk.hasFailures()) {
            List<String> collect = Arrays.stream(bulk.getItems()).map(item -> item.getId()).collect(Collectors.toList());
            log.info("商品上架错误skuIds: {},原因: {}", collect, bulk.buildFailureMessage());
        }
        return !bulk.hasFailures();
    }
}
